import { reactive } from 'vue'

interface UnreadKey {
  deviceId: string
  wxId: string
}

export interface ToastItem {
  id: string
  title: string
  content: string
  timestamp: number
  durationMs?: number
}

function makeKey({ deviceId, wxId }: UnreadKey) {
  return `${deviceId}::${wxId}`
}

export const messageStore = reactive({
  // key: `${deviceId}::${wxId}` -> count
  unreadMap: new Map<string, number>(),
  toasts: [] as ToastItem[],

  incrementUnread(deviceId: string, wxId: string) {
    const key = makeKey({ deviceId, wxId })
    const current = this.unreadMap.get(key) || 0
    this.unreadMap.set(key, current + 1)
  },

  clearUnread(deviceId: string, wxId: string) {
    const key = makeKey({ deviceId, wxId })
    this.unreadMap.delete(key)
  },

  getUnread(deviceId: string, wxId: string): number {
    const key = makeKey({ deviceId, wxId })
    return this.unreadMap.get(key) || 0
  },

  removeToast(id: string) {
    const idx = this.toasts.findIndex(t => t.id === id)
    if (idx !== -1) this.toasts.splice(idx, 1)
  },

  pushToast(title: string, content: string, durationMs = 60000) {
    const id = `${Date.now()}-${Math.random()}`
    const item: ToastItem = { id, title, content, timestamp: Date.now(), durationMs }
    this.toasts.push(item)
    if (this.toasts.length > 5) this.toasts.shift()
    // 自动移除
    setTimeout(() => {
      this.removeToast(id)
    }, durationMs)
  }
}) 